package com.cxw.healthserver.service

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper
import com.cxw.healthserver.entity.Archive
import com.cxw.healthserver.entity.SignConfig
import com.cxw.healthserver.entity.SignInfo
import com.cxw.healthserver.mapper.SignConfigMapper
import com.cxw.healthserver.mapper.SignInfoMapper
import com.cxw.healthserver.response.BaseResponse
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.ObjectMapper
import org.json.JSONObject
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

/**
 * @createTime 2024/6/25 22:44
 * @author 崔兴旺
 * @description
 */
@Service
class SignInfoService {
    @Autowired
    private lateinit var residentService: ResidentService

    @Autowired
    private lateinit var signInfoMapper: SignInfoMapper
    @Autowired
    private lateinit var signConfigMapper: SignConfigMapper

    @Autowired
    private lateinit var objectMapper: ObjectMapper

    fun querySignInfo(username: String, idNumber: String): JsonNode? {
        val archive = signInfoMapper.selectOne(QueryWrapper<SignInfo>().eq("username", username).eq("idNumber", idNumber))
        if (archive != null) {
            return objectMapper.readTree(archive.json)
        }
        return null
    }


    fun saveSignInfo(username: String, jsonStr: String): BaseResponse<Any> {
        val jsonObject = JSONObject(jsonStr)
        val idNumber = jsonObject.optString("idNumber", null)
        if (idNumber.isNullOrBlank()) {
            return BaseResponse.fail("签约信息中缺少idNumber")
        }
        var signInfo = signInfoMapper.selectOne(QueryWrapper<SignInfo>().eq("username", username).eq("idNumber", idNumber))
        var isAdd = false
        if (signInfo == null) {
            signInfo = SignInfo()
            isAdd = true
        }
        signInfo.username = username
        signInfo.idNumber = idNumber
        signInfo.json = jsonStr
        val rows = if (isAdd) {
            signInfoMapper.insert(signInfo)
        } else {
            signInfoMapper.updateById(signInfo)
        }
        if (rows >= 0) {
            residentService.recordHasSignInfo(username,idNumber)
            return BaseResponse.success(null)
        }
        return if (isAdd) {
            BaseResponse.fail("新增签约信息失败,rows:${rows}")
        } else {
            BaseResponse.fail("更新签约信息失败,rows:${rows}")
        }
    }
}